var userid = '';
var add;
var del;
var lock;
var update;
var getInfo;
var empowersb;
var resetpwd;
$(document).ready(function(){
	cw.common.getUserSession(validatePermission,true);
})

//验证权限
function validatePermission(userinfo){
	userid = userinfo.USER_ID;
	var permissionNames = "add,del,lock,update,getInfo,empowersb,resetpwd";
	var actionNames = "ADD_T_SYS_USER_ACTION,DELETE_T_SYS_USER_ACTION,UPDATE_SYS_USER_ISLOCK_ACTION,UPDATE_T_SYS_USER_ACTION,";
	actionNames += "GET_T_SYS_USER_ACTION,MANAGE_USER_PERMISSION_ACTION,RESET_SYS_USER_PASSWORD_ACTION";
	cw.common.hasPermission(permissionNames,actionNames,isShow);
	getUserList();
}
//是否显示操作按钮
function isShow(data){
	var obj = data.root.PERMISSION.rs[0];
	if(obj.add){
		$('#add').html('<a href="addUser.html"><img src="../images/anniu16.gif"/></a>');
	}
	del = obj.del;
	if(del){
		$('#batchDel').html('<a href="javascript:batchDelUser()">批量删除</a>');
	}
	update = obj.update;
	lock = obj.lock;
	getInfo = obj.getInfo;
	empowersb = obj.empowersb;
	resetpwd = obj.resetpwd;
}

function getUserList(){
	var url = cw.common.path + '/json?action=QUERY_T_SYS_USERBY_PAGER_ACTION';
	url += "&LOGIN_NAME="+$('#LOGIN_NAME').val()+"&USERNAME="+$('#USER_NAME').val()+"&ISLOCK="+$('#ISLOCK').val();
	var xmlname = "T_SYS_USER";
	var pagePanel='#pager';
	var result='#userlist';
	var pageSize=10;
	var defaultHtml='<li><em style="text-align: center;width:100%">没有搜索到您要查询的数据...</em></li>';
	cw.common.changePage(url,pageSize,xmlname,result,fn_getUserList,pagePanel,defaultHtml);
}

function fn_getUserList(obj,result,i){
	var str = "<li>";
	str += "<em style='width: 9%; text-align: center;'><input type='checkbox' name='check' value='"+obj.USER_ID+"' /></em>";
	str += "<em style='width: 10%; text-align: center;'>"+obj.LOGIN_NAME+"</em>";
	str += "<em style='width: 15%; text-align: center;''>"+obj.USER_NAME+"</em>";
	str += "<em style='width: 15%; text-align: center;''>"+obj.ROLE_NAME+"</em>";
	var status = "";
	if(obj.IS_LOCK == 0){
		status = "未锁定";
	}
	else if(obj.IS_LOCK == 1){
		status = "已锁定";
	}
	str += "<em style='width: 15%; text-align: center;''>"+status+"</em>";
	str += "<em style='width: 35%; text-align: center;'>";
	if(userid != obj.USER_ID && obj.USER_ID != 1){
		if(getInfo){
			str += "<a href='userDetail.html?id="+obj.USER_ID+"'>查看</a> ";
		}
		if(update){
			str += "<a href='updateUser.html?id="+obj.USER_ID+"'>修改</a> ";
		}
		if(empowersb){
			str += "<a href='javascript:showDialog("+obj.USER_ID+",\""+obj.USER_NAME+"\")'>权限分配</a> ";
		}
		if(lock){
			var flag = "";
			if(obj.IS_LOCK == 0){
				flag = "锁定";
			}
			else if(obj.IS_LOCK == 1){
				flag = "解锁";
			}
			str += "<a href='javascript:updateLock("+obj.USER_ID+",\""+obj.IS_LOCK+"\")'><span id='lock"+obj.USER_ID+"'>"+flag+"</span></a> ";
		}
		if(del){
			str += "<a href='javascript:delUser("+obj.USER_ID+",\""+obj.LOGIN_NAME+"\")'>删除</a> ";
		}
		if(resetpwd){
			str += "<a href='javascript:resetPWD("+obj.USER_ID+")'>重置密码</a>";
		}
		if(!getInfo && !update && !empowersb && !del && !lock && !resetpwd){
			str += "您无操作权限";
		}
	}
	else{
		str += "(不允许操作当前用户与管理员)";
	}
	str += "</em></li>";
	$(result).append(str);
}

function updateLock(userid, islock){
	var status = '';
	if(islock == '0'){
		status = "锁定";
	}
	else{
		status = "解锁";
	}
	if(confirm("您确定要"+status+"该用户吗？")){
		$.post(cw.common.path + '/json?action=UPDATE_SYS_USER_ISLOCK_ACTION',{
			USER_ID : userid,
			IS_LOCK : islock
		},function(data){
			if(data.success){
				alert(status+"成功");
				window.location.href = document.URL;
			}
			else{
				alert(data.errors.errmsg);
			}
		},'json');
	}
}

//重置密码
function resetPWD(userid){
	if(confirm("您确定要重置该用户的密码吗？")){
		$.post(cw.common.path + '/json?action=RESET_SYS_USER_PASSWORD_ACTION',{
			USER_ID : userid
		},function(data){
			if(data.success){
				alert("重置密码成功");
			}
			else{
				alert(data.errors.errmsg);
			}
		},'json');
	}
}

//删除用户
function delUser(userid,loginName){
	if(confirm("是否确定删除"+loginName+"的帐号信息？")){
		var url = cw.common.path + '/json?action=DELETE_T_SYS_USER_ACTION&USER_ID='+userid;
		$.post(url,{},function(data){
			if(data.success){
				alert('已成功删除系统帐号'+loginName+'！');
				location.href = document.URL;
			} else {
				alert(data.errors.errmsg);
			}
		},'json');
	}
}

//批量删除
function batchDelUser(){
	if(getCheckedNum('check')==0){
		alert('请选择要删除的用户');
		return;
	}
	if(!confirm('确定要删除用户吗？')){
		return;
	}
	$.post(cw.common.path + '/json',
		{
			action : 'BATCH_DELETE_T_SYS_USER_ACTION',
			USER_ID : getCheckedVal('check').split(',')
		}, function(data){
			if (data.success) {
				alert('批量删除用户成功');
				location.href = document.URL;
			} else {
				alert(data.errors.errmsg);
			}
		}, 'json');
}

//显示用户权限
function showDialog(userid, userName){
	var content = '';
	content += '<div style="text-align:center;border:1px dotted;background:#999999;padding: 5px; margin-bottom:10px;">';
	content += '注意事项：凡模块有分配了修改删除等权限的，都必须分配查询权限，用户才能正常操作</div>';
	content += '<table width="80%" align="center">';
	content += '<tr><td valign="top"><span id="tree_role">数据载入中...</span></td>';
	content += '<td valign="top"><span id="tree_function"></span></td></tr>';
	content += '</table><div align="center" style="padding-top:5px;">';
	content += '<input type="button" id="stb" value="授权" onclick="managerUserPermission('+userid+')" style="display:none"/></div>';
	dialog("用户授权","text:"+content,"550px","auto","floatPoint");
	setTimeout('loadTree('+userid+',"'+userName+'")',1000);
}

//载入用户权限
function loadTree(userid, userName){
	loadRoleTree(userid,userName);
	loadFunctionTree(userid,userName);
	$('#stb').show();
}

//角色树
var treeRole;
function loadRoleTree(userId,userName){
	treeRole = new dTree('treeRole',cw.common.path+'/common/dtree/images');
	treeRole.add(1, -1, userName+'角色');
	$.post(cw.common.path+'/json',
		{
			action : 'QUERY_USER_ROLE_TREE_ACTION',
			USER_ID : userId
		}, function(data){
			if (data.success) {
				var length = data.root.T_USER_ROLE.rs.length;
				if(length > 0){
					for(var i=0;i<length;i++) {
						var obj=data.root.T_USER_ROLE.rs[i];
						treeRole.add(obj.ROLE_ID, 1, 'ROLE_ID', obj.ROLE_ID, obj.ROLE_NAME, 
							obj.IS_USER_ROLE, null, null, null, null, null, null, obj.IS_USER_ROLE);
					}
					$('#tree_role').html(treeRole.toString());
				}
				else{
					$('#tree_role').html('暂无角色信息');
				}
			} else {
				alert(data.errors.errmsg);
			}
		}, 'json');
}

//功能树
var treeFunction;
function loadFunctionTree(userId,userName){
	treeFunction = new dTree('treeFunction',cw.common.path+'/common/dtree/images');
	treeFunction.add(0,-1,userName+'功能');
	$.post(cw.common.path+'/json',
		{
			action : 'QUERY_FUNCTION_TREE_ACTION_BY_PK_USER',
			USER_ID : userId
		}, function(data){
			if (data.success) {
				var length = data.root.T_ALL_FUNCTION.rs.length;
				for(var i=0;i<length;i++) {
					var obj=data.root.T_ALL_FUNCTION.rs[i];
					treeFunction.add(obj.FUNCTION_ID, obj.PARENT_FUNCTION==''?0:obj.PARENT_FUNCTION,
						'FUNCTION_ID', obj.FUNCTION_ID, obj.FUNCTION_NAME, 
						obj.IS_USER_FUNCTION, obj.IS_USER_FUNCTION, null, null, null, null, null, obj.IS_USER_FUNCTION);
				}
				$('#tree_function').html(treeFunction.toString());
				var lengthX = data.root.T_APPEND_FUNCTION.rs.length;
				for(var i = 0; i < lengthX; i++){
					var obj=data.root.T_APPEND_FUNCTION.rs[i];
					$('#FUNCTION_ID_'+obj.FUNCTION_ID).attr('disabled',false);
				}
				//角色树绑定事件
				var chkRole = document.getElementsByName("ROLE_ID");
				for(var i=0;i<chkRole.length;i++){
					$('#'+chkRole[i].id).click(function(){
						var chkFunction=document.getElementsByName("FUNCTION_ID");
						for(var i=0;i<chkFunction.length;i++){
							chkFunction[i].checked=false;
							chkFunction[i].disabled=false;
						}
						for(var i=0;i<chkRole.length;i++){
							if(chkRole[i].checked){
								$.post(cw.common.path+'/json',
									{
										action : 'QUERY_FUNCTION_TREE_ACTION_BY_PK_ROLE',
										ROLE_ID : chkRole[i].value
									}, function(data){
										if (data.success) {
											var lengthY = data.root.T_SYS_FUNCTION.rs.length;
											for(var i=0;i<lengthY;i++) {
												var obj=data.root.T_SYS_FUNCTION.rs[i];
												if(obj.IS_ROLE_FUNCTION){
													$('#FUNCTION_ID_'+obj.FUNCTION_ID).attr('checked',obj.IS_ROLE_FUNCTION);
													$('#FUNCTION_ID_'+obj.FUNCTION_ID).attr('disabled',obj.IS_ROLE_FUNCTION);
												}
											}
										} else {
											alert(data.errors.errmsg);
										}
									}, 'json'
								);
							}
						}					
					});
				}
			} else {
				alert(data.errors.errmsg);
			}
		}, 'json'
	);
}

function managerUserPermission(userId){
	var roleobj = document.getElementsByName("ROLE_ID");
	var roleIds = [];
	for(i = 0; i < roleobj.length; i++){
		if(roleobj[i].checked){
			roleIds[roleIds.length] = roleobj[i].value;
		}
	}
	var funobj = document.getElementsByName("FUNCTION_ID");
	var functionIds = [];
	for(i = 0;i < funobj.length; i++){
		if(funobj[i].checked){
			if(!funobj[i].disabled){
				functionIds[functionIds.length] = funobj[i].value;
			}
		}
	}
	if(roleIds.length == 0 && functionIds.length == 0){
		alert("请为用户分配权限");
		return;
	}
	$.post(cw.common.path+'/json',
		{
			action : 'MANAGE_USER_PERMISSION_ACTION',
			USER_ID : userId,
			ROLE_ID : roleIds,
			FUNCTION_ID : functionIds
		}, function(data){
			if (data.success) {
				alert('授权成功');
		//		dialogclose();
			} else {
				alert(data.errors.errmsg);
			}
		}, 'json');
}
